<template>
  <div class="course-week">
    <div class="week-top">
      <div class="week-btn-wrap">
        <span @click="getLastWeek">上周</span>
        <span @click="getCurWeek">本周</span>
        <span @click="getNextWeek">下周</span>
      </div>
      <span>
        <el-button
          ref="button"
          type="text"
          class="rearrange"
          @click="handleRearrange"
        >{{ rearrangeFlag == true ? "重排" : "排班" }}</el-button>
      </span>
      <span class="editSwitch">
        <el-switch
          v-model="editStatus"
          active-text="编辑模式"
          inactive-text="展示模式"
          active-color="#13ce66"
          :disabled="lock"
          @change="handleStatusChange"
        /></span>
      <span class="w-today-date"> {{ todayDate }}</span>
    </div>
    <div class="week-table">
      <!-- 日期部分 -->
      <div class="table-header">
        <!-- 日期部分 -->
        <div class="table-week">
          <template v-for="(item, index) of weeks">
            <span v-if="index === 0" :key="weeks[index]" class="w-first">{{
              item
            }}</span>
            <span v-else>{{ item }}</span>
          </template>
        </div>
        <!-- 顶部日期部分 -->
        <div class="w-table-date">
          <template v-for="(item) of months">
            <template>
              <span
                :key="item.date"
                class="w-day-item"
                :class="{ 'w-isCurDate': item && item.isCurDate }"
              >
                {{
                  `${
                    item && item.isCurDate
                      ? (item && item.showDate + "(今天)") || ""
                      : (item && item.showDate) || ""
                  }`
                }}
              </span>
            </template>
          </template>
        </div>
      </div>

      <!-- 数据部分 -->
      <div class="w-time-period-list">
        <ul class="flex-row">
          <!--循环时段，看时段有多少个-->
          <template v-if="planList.length > 0">
            <li
              v-for="(period, p_index) in planList"
              :key="`period${p_index}`"
              class="w-time-period-row"
            >
              <div class="w-row-day">
                <div v-if="period.dayShiftList.length == 0" class="empty">
                  暂无排班
                </div>
                <template v-for="(dayShiftList) in period.dayShiftList" v-else>
                  <div class="w-things w-things-item">
                    <slot
                      name="thing"
                      :row="JSON.parse(JSON.stringify(dayShiftList))"
                    />
                  </div>
                </template>
              </div>
            </li>
          </template>
          <div v-else class="w-noMore"><span>暂无数据</span></div>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { formatDate, getCurDay } from '@/utils/MyTools'
export default {
  name: 'MyWschedule',
  props: {
    planList: {
      type: Array,
      default: []
    },
    // 第一列是星期几
    isFirstDayOfMondayOrSunday: {
      type: Number,
      default: 1
    },
    hasNumExpend: {
      type: Number,
      default: 2
    },
    rearrangeFlag: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      weeks: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      todayDate: '',
      months: [],
      curDate: '',
      nowDate: new Date(),
      editStatus: false,
      lock: false,
      showStaus: true
    }
  },
  watch: {
    isFirstDayOfMondayOrSunday: {
      handler(val) {
        if (val > 1) {
          const arr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          const arr1 = arr.slice(val)
          const arr2 = arr.slice(0, val)

          this.weeks = [...arr1, ...arr2]
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.getCurWeek()
  },
  methods: {
    // 获取时间
    getWeek(time) {
      this.curDate = new Date(time)
      // 当前是周几
      const whichDay = time.getDay()
      // const whichDay = this.curDate.getDay();
      // console.log(this.curDate);
      // console.log("whichDay",whichDay);
      // console.log("isFirstDayOfMondayOrSunday",this.isFirstDayOfMondayOrSunday);
      let num = 0
      if (this.isFirstDayOfMondayOrSunday <= whichDay) {
        num = this.isFirstDayOfMondayOrSunday
      } else {
        num = this.isFirstDayOfMondayOrSunday - 6
      }
      // console.log("num",num);
      const weekDay = time.getDay() - num < 0 ? 6 : time.getDay() - num
      // const weekDay = (this.curDate.getDay() - num)<0?6:(this.curDate.getDay() - num);
      // console.log("weekDay",weekDay)
      time = this.addDate(time, weekDay * -1)
      // time = this.addDate(this.curDate, weekDay * -1);
      // console.log("time",time);
      for (let i = 0; i < 7; i++) {
        const { year, month, day } = formatDate(
          i === 0 ? time : this.addDate(time, 1)
        )
        this.months.push({
          date: `${year}-${month}-${day}`,
          showDate: `${month}-${day}`,
          timestamp: new Date(`${year}-${month}-${day}`).getTime()
        })
      }
      this.months.sort((a, b) => a.timestamp - b.timestamp)
      delete this.months[0]
      const tempmonths = []
      for (let i = 0; i < this.months.length - 1; i++) {
        tempmonths[i] = this.months[i + 1]
      }
      this.months = tempmonths
      // console.log(this.months);
      this.todayDate = `${this.months[0].date} ~ ${
        this.months[this.months.length - 1].date
      }`
      // console.log(this.months)
    },
    // 日期处理
    addDate(date, n) {
      date.setDate(date.getDate() + n)
      return date
    },
    // 上周
    getLastWeek() {
      const date = this.addDate(this.curDate, -7)
      const { year, month, day } = formatDate(date)
      const dateObj = {
        date: `${year}-${month}-${day}`,
        timestamp: new Date(`${year}-${month}-${day}`).getTime()
      }
      this.dealDate(date)
      this.$emit('changeWeek', dateObj)
    },
    // 本周
    getCurWeek() {
      const { year, month, day } = formatDate(new Date())
      const dateObj = {
        date: `${year}-${month}-${day}`,
        timestamp: new Date(`${year}-${month}-${day}`).getTime()
      }
      this.dealDate(new Date())
      this.$emit('changeWeek', dateObj)
    },
    // /下周
    getNextWeek() {
      const date = this.addDate(this.curDate, 7)
      const { year, month, day } = formatDate(date)
      const dateObj = {
        date: `${year}-${month}-${day}`,
        timestamp: new Date(`${year}-${month}-${day}`).getTime()
      }
      this.dealDate(date)
      this.$emit('changeWeek', dateObj)
    },
    // 当前日期
    dealDate(date) {
      this.months = ['']
      this.getWeek(date)
      const curDate = getCurDay()
      this.months.forEach((item) => {
        item.isCurDate = item.date === curDate
      })
    },
    // 处理排班
    handleRearrange() {
      const promptInformation =
        this.rearrangeFlag == true
          ? '此操作将会重新为当周进行一次排班，是否确认进行此操作？'
          : '此操作将会进行一次排班，是否确认进行此操作？'
      this.$confirm(promptInformation, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const obj = {}
          obj.date = this.months[0].date
          obj.storeId = this.$store.getters.storeId
          obj.m = 0
          // console.log("按周重排班对象",obj);
          this.$emit('handleRearrange', obj)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 处理排班表状态变化
    handleStatusChange() {
      const msg = this.editStatus == false ? '展示' : '编辑'
      this.$notify({
        title: `${msg}模式`,
        message: `你已成功切换至${msg}模式`,
        type: 'success',
        duration: 2000
      })
      if (msg == '编辑') {
        this.$alert('你可以通过单击任一排班表进行排班', '', {
          confirmButtonText: '确定'
        })
      }
      this.$emit('handleStatusChange', this.editStatus)
      this.lock = true
      setTimeout(() => {
        this.lock = false
      }, 3000)
    },
    // 自动重排
    AutoRearrange() {
      const obj = {}
      // console.log(this.months[0].date);
      obj.date = this.months[0].date
      obj.storeId = this.$store.getters.storeId
      obj.m = 0
      // console.log("按周重排班对象",obj);
      this.$emit('handleRearrange', obj)
    }
  }
}
</script>

  <style>
.empty {
  height: 90px;
  line-height: 90px;
  text-align: center;
}
.test {
  position: absolute;
  top: 500px;
  left: 500px;
}

ul {
  list-style: none;
}
ul,
li {
  margin: 0;
  padding: 0;
}
.course-week {
  width: 100%;
  border: 1px solid #ddd;
  padding: 1%;
  box-sizing: border-box;
}
.week-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 40px;
  padding: 0 1%;
  box-sizing: border-box;
  min-width: 600px;
}
.week-top .week-btn-wrap {
  width: 200px;
  display: flex;
  justify-content: space-around;
  color: #409eff;
}
.week-top .week-btn-wrap span {
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 15px;
}
.w-today-date {
  font-weight: bold;
  font-size: 16px;
}
.w-choose-status {
  display: flex;
  justify-content: flex-end;
  width: 200px;
}
.w-choose-status > div {
  width: 100%;
  flex: 1;
  display: flex;
  padding: 0 2%;
  white-space: nowrap;
  line-height: 20px;
  box-sizing: border-box;
}
.w-choose-status > div .square {
  display: flex;
  width: 16px;
  height: 16px;
  border-radius: 4px;
  box-sizing: border-box;
}
.w-choose-status > div .title {
  display: flex;
  align-items: center;
  line-height: 16px;
  padding-left: 4px;
  font-size: 14px;
  box-sizing: border-box;
}
.week-table {
  display: flex;
  flex-direction: column;
  /* border: 1px solid black; */
  width: 100%;
  min-width: 600px;
}
.week-table .table-header {
  width: 100%;
  height: 80px;
  background: #eaedf2;
  display: flex;
  flex-direction: column;
  align-items: center;
  border-bottom: 1px solid #eaedf2;
  box-sizing: border-box;
}
.table-header .w-table-date,
.table-week {
  width: 100%;
  height: 40px;
  text-align: left;
  display: flex;
  justify-content: center;
  align-items: center;
}
.table-header .w-table-date > span,
.table-week > span {
  flex: 1;
  color: #000;
  height: 100%;
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
}
.w-table-date .w-day-item,
.table-week .w-day-item {
  color: #000;
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.week-table .w-time-period-list {
  margin-top: 10px;
  width: 100%;
}
.flex-row {
  display: flex;
  flex-direction: row;
}
.w-time-period-list .w-time-period-row {
  width: 100%;
  min-height: 60px;
  cursor: pointer;
  /* border: 1px solid red; */
}
.w-time-period-col {
  width: 100%;
  min-height: 60px;
  display: flex;
  flex-direction: column;
}
.w-time-period-col .w-time-period {
  width: 12.5%;
  display: flex;
  justify-content: center;
  align-items: center;
  border-left: 1px solid #eaedf2;
  border-bottom: 1px solid #eaedf2;
  border-right: 1px solid #eaedf2;
  box-sizing: border-box;
}
.w-time-period-col .w-row-day {
  width: 87.5%;
  min-height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.w-row-day .w-things {
  flex: 1;
  display: flex;
  max-width: 500px;
  min-height: 100px;
  background-color: #3291f8;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  border-left: 1px solid #eaedf2;
  border-bottom: 1px solid #eaedf2;
  border-right: 1px solid #eaedf2;
  box-sizing: border-box;
  padding: 10px;
}
.w-row-day .w-things:last-child {
  border-right: 1px solid #eaedf2;
}
.w-things .w-things-item {
  display: flex;
  width: 10%;
  font-size: 14px;
  flex-direction: column;
  justify-content: space-around;
  height: 200px;
  border-radius: 10px;
  margin: 2% 1%;
  padding: 1% 2%;
  cursor: pointer;
  color: #fff;
  background: #ff6200;
  box-sizing: border-box;
  transition: all 1s linear 0.5s;
}
.w-isCurDate {
  color: #ff2525 !important;
}
.w-noMore {
  width: 100%;
  min-height: 200px;
  padding: 2%;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid rgba(156, 173, 173, 0.3);
  color: #9cadadb7;
  box-sizing: border-box;
}
.w_expand,
.w_shrink {
  color: #0a98d5;
  cursor: pointer;
  width: 100%;
  padding: 2% 0;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}
.rearrange {
  margin-left: 20px;
  padding: 10px;
  width: 60px;
  border: 1px solid rgb(230, 228, 228);
  color: black;
  font-weight: 300;
}
</style>
